package server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server implements Runnable{
	
	ServerSocket serverSocket = null;
	private boolean running = true;
	
	public Server(){
		// create server socket
		try {
			serverSocket = new ServerSocket(5000);
		} catch (IOException e) {
			System.err.println("Port " + 5000 + " not available.");
			e.printStackTrace();
			System.exit(1);
		}
	}
	
	public synchronized void setRunning(boolean running){
		this.running = running;
		if (running == false){
			try {
				serverSocket.close();
			} catch (IOException e) {
				
			}
		}
	}
	
	public synchronized boolean isRunning(){
		return running;
	}

	@Override
	public void run() {
		while(isRunning()){
			Socket clientSocket = null;
			
			try{
				clientSocket = serverSocket.accept();
			} catch (IOException e){
				System.err.println("Accept failed");
			}
			
			final Socket cs = clientSocket;
			
			Thread t1 = new Thread(new Runnable() {				
				@Override
				public void run() {					
					if (cs != null){
						System.out.println(cs.getInetAddress());
						new SocketHandler(cs);
					} else {
						System.err.println("No socket acquired from accept");
					}
				}
			});
			t1.start();
		}
	}
	
	public static void main(String[] args){
		Server server = new Server();
		server.run();
	}
}
